package com.campus.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.api.util.UserContext;
import com.campus.common.result.Result;
import com.campus.common.student.job.entity.Student;
import com.campus.common.student.mapper.StudentMapper;
import com.campus.common.user.entity.pojo.User;
import com.campus.common.user.mapper.AuthMapper;
import com.campus.course.dto.entity.CourseRecords;
import com.campus.course.dto.entity.CourseSchedule;
import com.campus.course.dto.entity.Courses;
import com.campus.course.dto.vo.CourseStudentsListVO;
import com.campus.course.mapper.CourseRecordsMapper;
import com.campus.course.mapper.CourseScheduleMapper;
import com.campus.course.mapper.CoursesMapper;
import com.campus.course.service.ICourseRecordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 选课记录表 服务实现类
 * </p>
 *
 * @author maojr
 * @since 2024-11-16
 */
@Service
public class CourseRecordsServiceImpl extends ServiceImpl<CourseRecordsMapper, CourseRecords> implements ICourseRecordsService {

    @Autowired
    private CourseRecordsMapper courseRecordsMapper;

    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private CourseScheduleMapper courseScheduleMapper;

    @Autowired
    private AuthMapper authMapper;


    @Override
    public Result stuChooseCourse(int courseId) {
        int userId = UserContext.getUserId();
        //获取学生学号(id)
        Student student = studentMapper.selectOne(
                new QueryWrapper<Student>().eq("user_id", userId)
        );
        Courses course = coursesMapper.selectById(courseId);
        //查询课程剩余容量
        if (course.getRemain() <= 0) {
            return Result.fail("选课失败，该课程人数已满",null);
        }

        //查询课程的安排是否与学生的课程冲突
        QueryWrapper<CourseRecords> recordsQueryWrapper = new QueryWrapper<>();
        recordsQueryWrapper.eq("student_id",student.getId());
        List<CourseRecords> stuRecords = courseRecordsMapper.selectList(recordsQueryWrapper);
        //先获取该课程的每节课
        List<CourseSchedule> scheduleList = courseScheduleMapper.selectList(
                new QueryWrapper<CourseSchedule>().eq("course_id", courseId)
        );
        //遍历学生所选课
        for (CourseRecords record : stuRecords) {
            QueryWrapper<CourseSchedule> scheduleQueryWrapper = new QueryWrapper<>();
            scheduleQueryWrapper.eq("course_id",record.getCourseId());
            List<CourseSchedule> schedules = courseScheduleMapper.selectList(scheduleQueryWrapper);
            //遍历每一种课的每一节课的时间，比对将选课
            for (CourseSchedule stuSchedule : schedules ) {
               for (CourseSchedule schedule : scheduleList) {
                   //对比具体时间
                   if (stuSchedule.getWeekDay() == schedule.getWeekDay() &&
                           stuSchedule.getDay() == schedule.getDay() &&
                           stuSchedule.getTime() == schedule.getTime()) {
                       return Result.fail("选课失败，该课程与已选课程第"+stuSchedule.getCourseId()+"周星期"+
                               stuSchedule.getWeekDay()+"第"+stuSchedule.getTime()+"节冲突。",null);
                   }
               }
            }
        }
        CourseRecords courseRecords = new CourseRecords();
        courseRecords.setCourseId(courseId);
        courseRecords.setStudentId(student.getId());
        courseRecords.setStatus(1);
        courseRecords.setAbsence(0);
        courseRecords.setChooseTime(LocalDateTime.now());
        courseRecordsMapper.insert(courseRecords);
        //课程容量减少
        course.setRemain(course.getRemain() - 1);
        coursesMapper.updateById(course);
        return Result.success("选课成功，记录已加入数据库。");
    }

    @Transactional
    @Override
    public Result stuCancelCourse(int courseId) {
        int userId = UserContext.getUserId();
        //获取学生学号(id)
        Student student = studentMapper.selectOne(
                new QueryWrapper<Student>().eq("user_id", userId)
        );
        Courses course = coursesMapper.selectById(courseId);
        //查找选课记录然后删除
        QueryWrapper<CourseRecords> recordsQueryWrapper = new QueryWrapper<>();
        recordsQueryWrapper.eq("student_id",student.getId())
                .eq("course_id",course.getId());

        int isDelete = courseRecordsMapper.delete(recordsQueryWrapper);
        if (isDelete > 0) {
            //课程剩余人数增加
            course.setRemain(course.getRemain() - 1);
            if (coursesMapper.updateById(course) > 0) {
                return Result.success("退课成功");
            }
            else {
                return Result.fail("退课失败，请稍后重试");
            }
        }
        else {
            return Result.fail("退课失败，请稍后重试");
        }
    }

    /**
     * 获取某个课程的学生名单
     */
    @Override
    public List<CourseStudentsListVO> courseStudentList(Integer courseId) {
        List<CourseRecords> courseRecordsList = courseRecordsMapper.selectList(new LambdaQueryWrapper<CourseRecords>()
                .eq(CourseRecords::getCourseId, courseId));
        List<CourseStudentsListVO> list = new ArrayList<>();
        courseRecordsList.forEach(courseRecords -> {
            Student student = studentMapper.selectById(courseRecords.getStudentId());
            User user = authMapper.selectById(student.getUserId());
            CourseStudentsListVO vo = new CourseStudentsListVO();
            vo.setId(courseRecords.getId());
            vo.setStudentId(courseRecords.getStudentId());
            vo.setName(user.getName());
            vo.setSex(user.getSex());
            vo.setAbsence(courseRecords.getAbsence());
            list.add(vo);
        });
        return list;
    }
}
